import 'package:flutter/material.dart';
import 'package:flutter_repository/repository/request_state.dart';
import 'package:get/get.dart';
import 'package:example_app/widgets/load_failed_widget.dart';

import 'loading_widget.dart';

typedef LoadWidgetBuilder<T> = Widget Function(BuildContext context, T data);

///简单封装的加载状态builder根据资源状态自动切换ui
class LoadBuilder<T> extends StatelessWidget {
  final Rx<Resource<T>> data;
  final LoadWidgetBuilder<T> builder;
  final VoidCallback? doRetry;
  const LoadBuilder(
      {Key? key, required this.data, required this.builder, this.doRetry})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Obx(() {
      if (data.value.isLoading) {
        return const LoadingWidget();
      }
      if (data.value.isSuccess) {
        return builder(context, data.value.data!);
      }
      if (data.value.isFailed) {
        return LoadFailed(
          doRetry: doRetry,
        );
      }
      return Container();
    });
  }
}
